﻿namespace S4sme.Domain.Queries.Post
{
    using System.Collections.Generic;
    using System.Linq;

    using Post = S4sme.Domain.Post;

    /// <summary>
    /// Query object to return all posts within specified category
    /// </summary>
    public static class FilterPostsExtension
    {
        public static IQueryable<Post> FindPagedRecentPosts(this IQueryable<Post> posts, int skip, int take, out int postCount, string tag = null, string category = null)
        {
            posts = posts.OrderByDescending(x => x.CreatedDate);

            if (tag != null)
            {
                posts = posts.Where(p => p.Tags.Any(t => t.Name == tag));
            }

            if (category != null)
            {
                posts = posts.Where(p => p.Categories.Any(c => c.Name == category));
            }

            // Note: posts.Skip(skip).Take(take) is not working in NHibernate 3.2 for SQLCE 4
            postCount = posts.Count(); // this will be returned as well to calculate the total pages
            var adjustedTake = take;

            // make sure the take value is within the collection range
            if (postCount < skip + adjustedTake)
            {
                adjustedTake = postCount - skip;
            }

            var copiedCol = posts.ToList();
            var newCol = new List<Post>();

            for (var i = skip; i < skip + adjustedTake; i++)
            {
                newCol.Add(copiedCol.ElementAt(i));
            }

            posts = newCol.AsQueryable();

            return posts;
        }
    }
}
